# -*- coding: utf-8 -*-
# @File: backend => user_view.py
# @CreateTime: 2025/8/26 11:05
# @Author: EvanZhang
# @Info: user api 接口的实现
from datetime import timedelta

from apps.models import User
from apps.schemas.user_schema import UserBase
from apps.utils.jwt import create_jwt_token


async def user_register(user) :
    try:
        existing_user = await User.get_or_none(username=user.username)
        if existing_user:
            return 400, '用户名已存在'
        new_user = await User.create(
            username=user.username,
            password_hash=user.password, # 密码传输前进行md5加密
        )
        return 201, '注册成功'
    except Exception as e:
        return 500, str(e) # 注册失败

async def user_login(user):
    try:
        existing_user = await User.get_or_none(username=user.username)
        if not existing_user or existing_user.password_hash != user.password:
            return 400,'用户名或密码错误' # 用户名或密码错误
        # 这里可以生成并返回一个JWT token
        access_token = create_jwt_token(
            data={"sub": user.username},
            expires_delta=timedelta(minutes=30)
        )

        # 更新数据,模型转字典,返回token
        userbase = UserBase(
            id=existing_user.id,
            username=existing_user.username,
            avatar_url=existing_user.avatar_url,
            chips=existing_user.chips,
            created_at=existing_user.created_at
        )
        token_dict= {"token": access_token}
        return 200,{'userinfo':userbase,'usertoken':token_dict} # 登录成功

    except Exception as e:
        return 500,e # 登录失败

def update_user_token(user):
    try:
        access_token = create_jwt_token(
            data={"sub": user.username},
            expires_delta=timedelta(minutes=30)
        )
        return 200, {"token": access_token}
    except Exception as e:
        return 500, str(e)

async def update_user_profile(username,img):
    try:
        existing_user = await User.get_or_none(username=username)
        if not existing_user:
            return 400,'用户不存在' # 用户不存在
        if img.avatar_url:
            existing_user.avatar_url = img.avatar_url
        await existing_user.save()
        return 201, '更新成功'
    except Exception as e:
        return 500, str(e) # 更新失败


